package datastructure;

import java.util.LinkedList;
import java.util.List;

/**
 * Author: Jason Wu
 * Date  : 2013-12-02
 */
public class BlockingQueue {

    private Object lock = new Object();

    private List queue = new LinkedList();
    private int limit = 10;

    public BlockingQueue(int limit) {
        this.limit = limit;
    }

    public void enqueue(Object item)
            throws InterruptedException {
        synchronized (lock) {
            while (this.queue.size() == this.limit) {
                System.out.println("waiting...");
                lock.wait();
            }
            if (this.queue.size() == 0) {
                lock.notify();
            }
            this.queue.add(item);
        }
    }

    public Object dequeue()
            throws InterruptedException {
        synchronized (lock) {
            while (this.queue.size() == 0) {
                lock.wait();
            }
            if (this.queue.size() == this.limit) {
                lock.notify();
            }

            return this.queue.remove(0);
        }
    }
}
